package com.wlz.base;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wlz
 * @date 2022-07-07  10:25 下午
 */
@Slf4j
public class MyNettyByteBuf {

    public static void main(String[] args) {

        // 创建byteBuf对象，该对象内部包含一个字节数组byte[10]
        // 通过readerindex和writerIndex和capacity，将buffer分成三个区域
        // 已经读取的区域：[0,readerindex)
        // 可读取的区域：[readerindex,writerIndex)
        // 可写的区域: [writerIndex,capacity)
        ByteBuf byteBuf = Unpooled.buffer(10);

        log.info("byteBuf = {}", byteBuf);

        for (int i = 0; i < 8; i++) {
            byteBuf.writeByte(i);
        }

        log.info("byteBuf = {}", byteBuf);

        for (int i = 0; i < 5; i++) {
            log.info("value = {}", byteBuf.getByte(i));
        }

        log.info("byteBuf = {}", byteBuf);

        for (int i = 0; i < 5; i++) {
            log.info("value = {}", byteBuf.readByte());
        }

        log.info("byteBuf = {}", byteBuf);

        //用Unpooled工具类创建ByteBuf
        ByteBuf byteBuf2 = Unpooled.copiedBuffer("hello,wlz!", CharsetUtil.UTF_8);
        // 使用 相关的方法
        if (byteBuf2.hasArray()) {
            byte[] content = byteBuf2.array();

            //将 content 转成字符串
            log.info("content = {}", new String(content,CharsetUtil.UTF_8));
            log.info("byteBuf2 = {}", byteBuf2);

            log.info("byteBuf2 = {}", byteBuf2.getByte(0));// 获取数组0这个位置的字符h的ascii码，h=104

            int len = byteBuf2.readableBytes();//可读的字节数  12
            log.info("len = {} ", len);

            //使用for取出各个字节
            for (int i = 0; i < len; i++) {
                log.info("char = {}", (char)byteBuf2.getByte(i));
            }

            //范围读取
            log.info("范围读取: {}", byteBuf2.getCharSequence(0,6, CharsetUtil.UTF_8));
            log.info("范围读取: {}", byteBuf2.getCharSequence(6,6, CharsetUtil.UTF_8));

        }

    }
}
